<template>
	<!--新增对话框-->
	<el-dialog
		:title="editForm.id ? '编辑' : '新增'"
		:visible.sync="dialogVisible"
		width="600px"
		:before-close="handleClose"
		:destroy-on-close="true"
	>
		<el-form :model="editForm" :rules="editFormRules" ref="editForm">
			<el-form-item label="报告年份" prop="reportDate" label-width="100px">
                <el-date-picker
                    v-model="editForm.reportDate"
                    type="year"
        			value-format="yyyy"
                    placeholder="选择年份">
                </el-date-picker>
			</el-form-item>
			<el-form-item label="省" prop="provinceOptions" label-width="100px">
				<el-cascader
				:options="provinceAndCityData"
				v-model="editForm.provinceOptions">
				</el-cascader>
			</el-form-item>
			<div>
				<div v-for="(item,index) in editForm.city_order" style="margin-bottom: 10px">
					<el-form-item label="城市排名" prop="itemHierarchy" label-width="100px">
						<el-col :span="8">
				<el-cascader
				:options="cityData"
				v-model="item.cityName">
				</el-cascader></el-col>
						<el-col :span="3"><el-input v-model="item.cityOrder" autocomplete="off"></el-input></el-col>
						<el-col :span="6"><el-input v-model="item.amount" autocomplete="off"></el-input></el-col>
						<el-col :span="4">
					<el-button type="danger" icon="el-icon-delete" size="mini" plain @click="removeCityOrder(index)">删除该项目</el-button>
						</el-col>
					</el-form-item>
				</div>
				<div style="text-align: center;margin-bottom: 10px;">
					<el-button type="primary" icon="el-icon-plus"  @click="editForm.city_order.push({cityName: '', cityOrder: '', amount:''})">增加城市排名</el-button>
				</div>
			</div>
			<div>
				<div v-for="(item,index) in editForm.emphasis_company" style="margin-bottom: 10px">
					<el-form-item label="企业" prop="itemHierarchy" label-width="100px">
						<el-col :span="6">
						<el-select v-model="item.key" placeholder="企业类型" clearable>
							<el-option label="造船企业" value="造船企业"></el-option>
							<el-option label="配套企业" value="配套企业"></el-option>
						</el-select>
						</el-col>
						<el-col :span="12"><el-input v-model="item.value" autocomplete="off"></el-input></el-col>
						<el-col :span="4">
					<el-button type="danger" icon="el-icon-delete" size="mini" plain @click="removeEmphasisCompany(index)">删除该企业</el-button>
						</el-col>
					</el-form-item>
				</div>
				<div style="text-align: center;margin-bottom: 10px;">
					<el-button type="primary" icon="el-icon-plus"  @click="editForm.emphasis_company.push({key: '', value: ''})">增加企业</el-button>
				</div>
			</div>
			<div>
				<div v-for="(item,index) in editForm.indicator" style="margin-bottom: 10px">
					<el-form-item label="指标" prop="itemHierarchy" label-width="100px">
						<el-col :span="8"><el-input v-model="item.key" autocomplete="off"></el-input></el-col>
						<el-col :span="10"><el-input v-model="item.value" autocomplete="off"></el-input></el-col>
						<el-col :span="4">
					<el-button type="danger" icon="el-icon-delete" size="mini" plain @click="removeIndicator(index)">删除该指标</el-button>
						</el-col>
					</el-form-item>
				</div>
				<div style="text-align: center;margin-bottom: 10px;">
					<el-button type="primary" icon="el-icon-plus"  @click="editForm.indicator.push({key: '', value: ''})">增加指标</el-button>
				</div>
			</div>
			<el-form-item v-if="type === '1'" label="描述" prop="description" label-width="100px">
                <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" v-model="editForm.description" autocomplete="off"></el-input>
			</el-form-item>
			<div v-else>
				<div v-for="(item,index) in editForm.description" style="margin-bottom: 10px">
					<el-form-item label="描述项" prop="itemHierarchy" label-width="100px">
						<el-col :span="8"><el-input v-model="item.key" autocomplete="off"></el-input></el-col>
						<el-col :span="8"><el-input v-model="item.value" autocomplete="off"></el-input></el-col>
						<el-col :span="6">
					<el-button type="danger" icon="el-icon-delete" size="mini" plain @click="removeDescription(index)">删除该项目</el-button>
						</el-col>
					</el-form-item>
				</div>
				<div style="text-align: center;margin-bottom: 10px;">
					<el-button type="primary" icon="el-icon-plus"  @click="editForm.description.push({key: '', value: ''})">增加描述项</el-button>
				</div>
			</div>
		</el-form>
		<div slot="footer" class="dialog-footer">
			<el-button @click="resetForm('editForm')">取 消</el-button>
			<el-button type="primary" @click="submitForm('editForm')">确 定</el-button>
		</div>
	</el-dialog>
</template>

<script>
import { provinceAndCityData, codeToText, pcaTextArr } from 'element-china-area-data';
import {formatServerDate} from '@/utils/date';
import {isString, isArray} from '@/utils/validate';
import TypeSelect from '@/components/typeSelect/Index.vue';
import ReportDatePicker from '@/components/reportDatePicker/Index.vue';
import TypeIdSelect from '@/components/typeIdSelect/Index.vue';
import { isNumber } from '@/utils/validate';
export default {
	name: 'AddUpdateShare',
	components: {
		ReportDatePicker,
		TypeSelect,
		TypeIdSelect,
	},
	props: {
		type: {
			type: String,
			default: '1',
		}
	},
	data() {
		return {
			editForm: {
				provinceOptions: [],
			},
			loading: false,
			dialogVisible: false,
			editFormRules: {
				report_date: [{ required: true, message: '请选择报告年月', trigger: 'blur' }],
			},
			// 只到省一级
			provinceAndCityData: provinceAndCityData.map((item) => {
				const {children, ...rest} = item;
				return {
					...rest
				}
			}),
			cityData:[],
		};
	},
	mounted() {
		// this.getFarmList('');
	},

	methods: {
		resetForm(formName) {
			this.$refs[formName].resetFields();
			this.dialogVisible = false;
			this.editForm = {
				provinceOptions: [],
			};
		},
		handleClose() {
			this.resetForm('editForm');
		},
		submitForm(formName) {
			this.$refs[formName].validate((valid) => {
				if (valid) {

                    const {reportDate, provinceOptions, city_order, description, emphasis_company, indicator, ...rest} = this.editForm;
					const params = {
                                reportDate: formatServerDate(reportDate, 'YYYY-MM'),
                                ...rest,
					};

					if(this.type === '1'){
						params['description'] = description;
					}else{
						params['description'] = JSON.stringify(description.filter(item => !!(item.value)));
					}

					params['city_order'] = JSON.stringify(city_order.filter(item => !!(item.cityOrder)));
					params['emphasis_company'] = JSON.stringify(emphasis_company.filter(item => !!(item.value)));
					params['indicator'] = JSON.stringify(indicator.filter(item => !!(item.value)));

					if(provinceOptions && provinceOptions[0]){
						params['district_code'] = `${provinceOptions[0]}0000`;
					}

					this.$axios
						.post('/admin/boat/yellow/' + (this.editForm.id ? 'edit' : 'edit'), params)
						.then((res) => {
							this.$message({
								showClose: true,
								message: '恭喜你，操作成功',
								type: 'success',
								onClose: () => {
									this.$emit('refreshDataList');
								},
							});
							this.dialogVisible = false;
							this.resetForm(formName);
						}).catch(e => {});
				} else {
					console.log('error submit!!');
					return false;
				}
			});
		},
		checkIsDisabledDate(date){
			console.log(date);
			return true;
		},
		init(id) {
			this.dialogVisible = true;
			if (id != null && id != '' && id > 0) {
				this.$axios.get('/admin/boat/yellow/detail?id=' + id).then((res) => {
                    const {result = {}} = res;
                    const { report_date, verify_status, district_code,indicator, city_order,description,emphasis_company,type_id, ...rest} = result;

					const provinceOptions = [];
					this.cityData = [];
					if(district_code){
						provinceOptions[0] = `${district_code.substring(0, 2)}`;
						const findProvince = provinceAndCityData.find((item) => item.value === provinceOptions[0]);
						if(findProvince){
							const {label} = findProvince;
							const options = pcaTextArr.find(item => item.label === label);
							if(options){
								this.cityData = options.children.map(item => {
									const {children, ...rest} = item;
									return {
										...rest,
									}
								});
							}
						}
					}
					console.log(0);


					let json_indicator = [];
					
					try{
						indicator ? JSON.parse(indicator) : [];
						if(isString(json_indicator)){
							json_indicator = JSON.parse(json_indicator)
						}
					} catch(e){
						console.log(e);
					}
					
					console.log(1);
                    this.editForm = {
						provinceOptions,
						reportDate: report_date,
						indicator: json_indicator,
						city_order: city_order ? JSON.parse(city_order) : [],
						description: this.type === '1' ? description : (description ? JSON.parse(description) : []),
						emphasis_company: emphasis_company ? JSON.parse(emphasis_company) : [],
						...rest,
                    };
					console.log(2);

					// 如果 type 不为1,则 indicator 应该是个数组，否则为字符串
					if(!(this.editForm.indicator)){
						this.editForm.indicator = [];
					}
					console.log(3);

					console.log('editform', this.editForm)

				}).catch(e => {});
			}else{
				this.editForm.provinceOptions = [];
			}
		},
		removeIndicator(index){
			this.editForm.indicator.splice(index, 1);
		},
		removeCityOrder(index){
			this.editForm.city_order.splice(index, 1);
		},
		removeDescription(index){
			this.editForm.description.splice(index, 1);
		},
		removeEmphasisCompany(index){
			this.editForm.emphasis_company.splice(index, 1);
		},
	},
};
</script>

<style scoped>
.avatar-uploader .el-upload {
	border: 1px dashed #d9d9d9;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
}
.avatar-uploader .el-upload:hover {
	border-color: #409eff;
}
.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	line-height: 178px;
	text-align: center;
}
.avatar {
	width: 178px;
	height: 178px;
	display: block;
}
</style>
